#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QTableWidgetItem>
#include "sqleditor.h"
#include "ui_sqleditor.h"

SqlEditor::SqlEditor(QWidget *parent, QSqlDatabase db) :
    QMainWindow(parent),
    ui(new Ui::SqlEditor)
{
    ui->setupUi(this);

    this->db = db;
    model = new QSqlTableModel(this, this->db);
    ui->tableView->setModel(model);

    QStringList tables = db.tables();
    ui->tableComboBox->addItems(tables);
}

SqlEditor::~SqlEditor()
{
    delete ui;
}

void SqlEditor::on_tableComboBox_currentIndexChanged(const QString &arg1)
{
    model->setTable(arg1);
    model->select();
}

void SqlEditor::on_addRowButton_clicked()
{
    QModelIndex current = ui->tableView->currentIndex();
    int row = current.row();
    if (row == -1)
        row = model->rowCount();
    model->insertRows(row, 1);
}

void SqlEditor::on_removeRowButton_clicked()
{
    QModelIndex current = ui->tableView->currentIndex();
    int row = current.row();
    if (row == -1)
        return;
    model->removeRow(row);
}

void SqlEditor::on_queryExecuteButton_clicked()
{
    ui->resultTable->clear();
    ui->resultTable->setRowCount(0);
    ui->resultTable->setColumnCount(1);

    QSqlQuery query = db.exec( ui->queryTextEdit->toPlainText() );
    QSqlError error = query.lastError();
    if (error.isValid()) {
        ui->resultTable->setRowCount(1);
        QTableWidgetItem* item = new QTableWidgetItem(error.text());
        ui->resultTable->setItem(0, 0, item);
        return;
    }

    // column
    int count = query.record().count();
    ui->resultTable->setColumnCount(count);
    QStringList headers;
    for (int i=0; i<count; ++i)
        headers.append( query.record().field(i).name() );
    ui->resultTable->setHorizontalHeaderLabels(headers);


    // data
    int r = 0;
    while (query.next()){
        ui->resultTable->insertRow(r);
        for (int c=0; c<count; ++c) {
            QTableWidgetItem* item = new QTableWidgetItem(query.value(c).toString());
            ui->resultTable->setItem(r, c, item);
        }
        ++r;
    }
}
